﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AutoMapper;
using BankApp.ExtraMvc;
using CommonApp.Models;
using IBS.Bll;
using IBS.Bll.AutoPayments;
using IBS.Bll.OperationDay;
using IBS.Bll.Tools;
using IBS.Model;
using IBS.ServiceContracts;
using log4net.Config;
using Client = CommonApp.Models.Client;

namespace BankApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new RequireHttpsAttribute());
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                );
        }

        protected void Mapping()
        {
            Mapper.CreateMap<UserRequest, Request>();
            Mapper.CreateMap<Request, UserRequest>();
            Mapper.CreateMap<Client, IBS.Model.Client>();
            Mapper.CreateMap<IBS.Model.Client, Client>();
        }

        protected void FillDataBase()
        {
            // SQLHelper.ClearAllTables();

            IBSHelper.FillStreets();
            IBSHelper.FillAddresses();
            IBSHelper.FillCurrencies();
            IBSHelper.FillIbsAndErip();
            IBSHelper.FillAssets();
            IBSHelper.FillCodeCards();
            IBSHelper.FillPayments();
            IBSHelper.FillClients();

        }

        protected void CreateRoles()
        {
            if (!Roles.RoleExists("admin"))
                Roles.CreateRole("admin");
            if (!Roles.RoleExists("operator"))
                Roles.CreateRole("operator");
            if (!Roles.RoleExists("user"))
                Roles.CreateRole("user");
        }


        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            XmlConfigurator.Configure();
            Mapping();
            bool isFirstRun = false;
            if (isFirstRun)
            {
                IBSHelper.ReCreateDataBase();
                CreateRoles();
                FillDataBase();
            }

            IBSHelper.SetNewDay();
            new IbsContainer().StartPaymentProcessor();
            new IbsContainer().StartAutoPaymentProcessor();
          
           
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            
           // ControllerBuilder.Current.SetControllerFactory(new BankAppControllerFactory());
            //Start AutoPayment Processor
            
        }



        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Response.Clear();

            HttpException httpException = exception as HttpException;

            // clear error on server
            Server.ClearError();
            string message = null;
            if (httpException != null)
            {
                switch (httpException.GetHttpCode())
                {
                    case 404:
                        message = "The page requested doesn't exist";
                        break;
                }
            }
            else if (exception is BusinessException || exception is InvalidOperationException)
            {
                message = exception.Message;
            }
            else
            {
                return;
            }
            
            var errorUrl = String.IsNullOrWhiteSpace(message)
                ? "~/Home/Error"
                : String.Format("~/Home/Error?msg={0}", new UrlHelper(Request.RequestContext).Encode(message));
            Response.Redirect(errorUrl);
        }
    }

}